package com.focusai.efairy.ui.activity.dev;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.focusai.efairy.R;
import com.focusai.efairy.business.manager.BeedManager;
import com.focusai.efairy.model.dev.DeviceItem;
import com.focusai.efairy.model.manager.CacheManager;
import com.focusai.efairy.model.msg.MsgItem;
import com.focusai.efairy.model.request.DevCmdControlRequest;
import com.focusai.efairy.model.request.GetDevMsgListRequest;
import com.focusai.efairy.model.request.GetDevUnhandleMsgListRequest;
import com.focusai.efairy.model.request.GetDeviceVersionInfoRequest;
import com.focusai.efairy.model.response.CurrentDeviceInfoResponse;
import com.focusai.efairy.model.response.DevMsgListResponse;
import com.focusai.efairy.model.response.DeviceUnHandleResponse;
import com.focusai.efairy.model.user.User;
import com.focusai.efairy.network.HttpManager;
import com.focusai.efairy.network.Response;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.ui.activity.warn.InputAlarmActivity;
import com.focusai.efairy.ui.activity.warn.WarnningDetailActivity;
import com.focusai.efairy.ui.adapter.msg.MsgChatLeftViewBinder;
import com.focusai.efairy.ui.adapter.msg.MsgChatRightViewBinder;
import com.focusai.efairy.ui.base.SwipeBackBaseActivity;
import com.focusai.efairy.ui.widget.BaseTitleView;
import com.focusai.efairy.ui.widget.PopWindowDevChatTipView;
import com.focusai.efairy.ui.widget.PopWindowDevChatTypeView;
import com.focusai.efairy.utils.CmdUtils;
import com.focusai.efairy.utils.DateUtils;
import com.focusai.efairy.utils.GsonHelper;
import com.focusai.efairy.utils.log.Log;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.TextMessage;
import me.drakeet.multitype.ClassLinker;
import me.drakeet.multitype.ItemViewBinder;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * Created by Luogw on 2017/8/21.
 */

public class DevChattingActivity extends SwipeBackBaseActivity implements View.OnClickListener, PtrHandler, PopWindowDevChatTypeView.OnViewItemClickLisenter {
    private static final String TAG = DevChattingActivity.class.getName();

    public static final String KEY_DEV_ITEM = "key_dev_item";
    private static final int REQUEST_CODE_ALARM = 100;
    private static final int REQUEST_CODE_CONFIG = 101;
    private static final int REQUEST_CODE_UPGRAD = 102;
    private RecyclerView mRecyclerView;
    private BaseTitleView mTitleView;
    private TextView textReset;
    private TextView textCancal;
    private TextView textPeizhi;
    private TextView tv_upgrade;//升级
    private PtrClassicFrameLayout ptrClassicFrameLayout;
    private DeviceItem detailInfo;
    private MultiTypeAdapter mAdapter;
    private String userId;
    private AtomicBoolean sending = new AtomicBoolean(false);
    private AtomicBoolean isGettingMsg = new AtomicBoolean(false);
    private AtomicBoolean canLoadMore = new AtomicBoolean(false);
    private AtomicBoolean isScrollTop = new AtomicBoolean(false);
    private static int pageSize = 20;
    private List<Object> mList;
    private CountDownTimer registerDownTimer = null; // 输入验证码倒计时
    private long sendTick = 0; //发送倒计时
    private PopWindowDevChatTypeView mDevChatTypeView;
    private PopWindowDevChatTipView chatTipView;
    private MsgChatLeftViewBinder msgChatLeftViewBinder;
    private boolean isSeleteType = false;//是否是可选择状态
    private boolean isAllSelect = false;//是否全选  true 全选
    private int total_rows=0;
    private ArrayList<Long> unhandlemsg_list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_chatting);
        initView();
        setDefaultValues();
        initCustomTitte();
    }

    @Override
    protected boolean hasActionBar() {
        return false;
    }

    private void initCustomTitte() {
        if (isSeleteType) {
            mTitleView.getmTextRight().setText(R.string.sure);
            mTitleView.getmTextRight().setBackgroundColor(getResources().getColor(R.color.white));
            mTitleView.getmBack().setVisibility(View.GONE);
            mTitleView.getmTextLeft().setVisibility(View.VISIBLE);
            mTitleView.getmTextLeft2().setVisibility(View.VISIBLE);
            mTitleView.getmTextLeft2().setText("全不选");
            mTitleView.getmTextLeft().setOnClickListener(this);
            mTitleView.getmTextLeft2().setOnClickListener(this);
        } else {
            mTitleView.getmTextRight().setText("");
            mTitleView.getmTextRight().setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_filter_bg));
            mTitleView.getmBack().setVisibility(View.VISIBLE);
            mTitleView.getmTextLeft().setVisibility(View.GONE);
            mTitleView.getmTextLeft2().setVisibility(View.GONE);
            mTitleView.getmBack().setOnClickListener(this);
        }
        mTitleView.getmTextRight().setOnClickListener(this);
        mTitleView.getmTextCenter().setText(detailInfo.efairydevice_name);
    }

    @Override
    protected void initView() {
        mRecyclerView = findView(R.id.rcyc_list);
        mTitleView = findView(R.id.title_view);
        ptrClassicFrameLayout = findView(R.id.recycler_view_frame);
        textReset = findView(R.id.tv_reset);
        textCancal = findView(R.id.tv_cancal);
        textPeizhi = findView(R.id.tv_set);
        tv_upgrade = findView(R.id.tv_upgrade);
        textReset.setOnClickListener(this);
        textCancal.setOnClickListener(this);
        textPeizhi.setOnClickListener(this);
        tv_upgrade.setOnClickListener(this);
        int userRoleLevel = CacheManager.getUserRoleLevel();
        if (userRoleLevel == User.NORMALUSER) {
            textPeizhi.setVisibility(View.GONE);
        }
    }


    Set<Long> set = new HashSet<>();

    @Override
    protected void setDefaultValues() {
        if (getIntent() != null) {
            detailInfo = (DeviceItem) getIntent().getSerializableExtra(KEY_DEV_ITEM);
        }
        if (detailInfo == null) {
            showToast("设备不存在");
            finish();
        }
        if (CacheManager.isNormalUser()) {
            findView(R.id.view_set_line).setVisibility(View.GONE);
            findView(R.id.tv_set).setVisibility(View.GONE);
        }
        userId = "user_" + CacheManager.getUserId();
        mAdapter = new MultiTypeAdapter();
        msgChatLeftViewBinder = new MsgChatLeftViewBinder(detailInfo.efairydevice_name);
        msgChatLeftViewBinder.setOnItemClickLisenter(new MsgChatLeftViewBinder.OnItemClickLisenter() {
            @Override
            public void onItemClick(MsgItem item) {
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onRedBtnClick(MsgItem item) {
                if (!isSeleteType) {
                    entrySelectedType();
                }
            }

            @Override
            public void onGreenBtnClick(MsgItem item) {
                Intent intent = new Intent(getContext(), WarnningDetailActivity.class);
                intent.putExtra(WarnningDetailActivity.KEY_MSG_ITEM, item);
                startActivity(intent);
            }

            @Override
            public void onAvaterBtnClick(MsgItem item) {
                Intent intent = new Intent(getContext(), DeviceDetailInfoActivity.class);
                intent.putExtra(DeviceDetailInfoActivity.DEVICE_ITEM, detailInfo);
                startActivity(intent);
            }

            @Override
            public void OnCheckedChange(MsgItem item,boolean ischeck) {
                if(isSeleteType){
                    if(ischeck){
                        set.remove(item.get_id());
                    }else{
                        set.add(item.get_id());


                    }
                }
            }
        });
        mAdapter.register(MsgItem.class).
                to(msgChatLeftViewBinder, new MsgChatRightViewBinder(getContext()))
                .withClassLinker(new ClassLinker<MsgItem>() {
                    @NonNull
                    @Override
                    public Class<? extends ItemViewBinder<MsgItem, ?>> index(@NonNull MsgItem msgItem) {
                        if (userId.equals(msgItem.get_from_id())) {
                            return MsgChatRightViewBinder.class;
                        } else {
                            return MsgChatLeftViewBinder.class;
                        }
                    }
                });
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mAdapter);
        mList = new ArrayList<>();
        mAdapter.setItems(mList);
        ptrClassicFrameLayout.setPtrHandler(this);
        mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                isScrollTop.set(!recyclerView.canScrollVertically(-1));
            }
        });
        clearUnreadMsgStatus();
        RongIMClient.setOnReceiveMessageListener(new RongIMClient.OnReceiveMessageListener() {
            @Override
            public boolean onReceived(Message message, int j) {
                TextMessage textMessage = (TextMessage) message.getContent();
                if (textMessage != null) {
                    MsgItem msgItem = GsonHelper.getInstance().fromJson(textMessage.getExtra(), MsgItem.class);
                    boolean isNew = true;//是否为新消息
                    boolean isDev = false;//是否为该设备的消息
                    if (mList != null && detailInfo != null && msgItem != null && !userId.equals(msgItem.get_from_id())) {
                        String deviceId = "device_" + detailInfo.efairydevice_id;
                        if (deviceId.equals(msgItem.get_from_id())) {
                            isDev = true;
                            for (int i = mList.size() - 1; i > 0; i--) {
                                MsgItem msgItem1 = (MsgItem) mList.get(i);
                                if (msgItem.get_id() == msgItem1.get_id()) {
                                    isNew = false;
                                    break;
                                }
                            }
                        }
                    }
                    if (isNew && isDev) {
                        BeedManager.startpalyBeed();
                        msgItem.setmsg_time(DateUtils.getSimpleCurrentDate2());//新加的消息时间，本来是用服务器返回的时间，但是怕服务器时间与手机时间不一致，所以这里统一用手机时间
                        mList.add(msgItem);
                        notifyDataSetChanged(true);
                    }
                }
                return false;
            }
        });
        getMsgData(true, true);
        findUnhandleMsgList();
    }

    /**
     * 发送消息
     *
     * @param isGetNewMsg 是否为获取新的消息
     * @param showButton  是否滚动到底部
     */
    private void getMsgData(final boolean isGetNewMsg, final boolean showButton) {
        if (isGettingMsg.get()) {
            return;
        } else {
            isGettingMsg.set(true);
        }
        HttpManager.getInstance().sendRequest(new GetDevMsgListRequest(detailInfo.efairydevice_id, isGetNewMsg ? 0 : getLastMsgId(), pageSize,
                                                                       mDevChatTypeView != null ? mDevChatTypeView.getType() : -1, new Response.Listener<DevMsgListResponse>() {
            @Override
            protected void onSuccess(DevMsgListResponse response) {
                if (response != null && response.device_msglist != null) {
                    if (isGetNewMsg) {
                        mList.clear();
                    }
                    if (isSeleteType && response.device_msglist != null && isAllSelect) { //进入选择模式，加载出的数据默认选择
                        for (MsgItem item : response.device_msglist) {
                            item.isSelected = true;
                        }
                    }
                    Collections.reverse(mList);
                    canLoadMore.set(response.device_msglist.size() == pageSize);
                    mList.addAll(response.device_msglist);
                    Collections.reverse(mList);
                    notifyDataSetChanged(showButton);
                } else {
                    canLoadMore.set(false);
                }
                isGettingMsg.set(false);
                ptrClassicFrameLayout.refreshComplete();

            }

            @Override
            protected void onFail(NetworkException exception) {
                isGettingMsg.set(false);
                ptrClassicFrameLayout.refreshComplete();
            }
        }));

    }

    private long getLastMsgId() {
        if (mList != null && mList.size() > 0) {
            Object object = mList.get(0);
            return ((MsgItem) object).get_id();
        }
        return 0;
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    /**
     * 控制指令，66-查询ccid，128-复位，129-消音
     */
    private void sendCmd(long deviceId, int cmd) {
        if (sending.get()) {
            showToastOnUiThread("正在发送控制指令");
            return;
        } else {
            sending.set(true);
        }
        addSendMsg(cmd);
        HttpManager.getInstance().sendRequest(new DevCmdControlRequest(deviceId, cmd, new Response.Listener<MsgItem>() {
            @Override
            protected void onSuccess(MsgItem response) {
                if (response != null) {
                    Log.D(TAG, response.get_content());
                }
                sending.set(false);
            }

            @Override
            protected void onFail(NetworkException exception) {
                doException(exception);
                sending.set(false);
            }
        }));
    }

    private void addSendMsg(int cmd) {
        String date = DateUtils.getSimpleCurrentDate2();
        MsgItem msgItem = new MsgItem();
        msgItem.setmsg_time(date);
        msgItem.set_from_id(userId);
        switch (cmd) {
            case CmdUtils.REMOTE_RESET:
                msgItem.set_content("远程复位");
                break;
            case CmdUtils.REMOTE_XIAOSHENG:
                msgItem.set_content("远程消声");
                break;
            case CmdUtils.DEVICE_UPGRADE:
                msgItem.set_content("设备升级");
                break;
            default:
                break;
        }
        mList.add(msgItem);
        notifyDataSetChanged(true);
    }

    public void startculTime() {
        initCountDownTimer();
        registerDownTimer.cancel();
        registerDownTimer.start();
    }

    private void initCountDownTimer() {
        if (registerDownTimer == null) {
            registerDownTimer = new CountDownTimer(11 * 1000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    sendTick = (millisUntilFinished / 1000);
                }

                @Override
                public void onFinish() {
                    sendTick = 0;
                }
            };
        }
    }

    private boolean checkSendTick() {
        long time = sendTick;
        if (time > 1) {
            showToast(time + "s后才能再次操作");
            return false;
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_cancal:
                if (detailInfo != null && checkSendTick()) {
                    sendCmd(detailInfo.efairydevice_id, CmdUtils.REMOTE_XIAOSHENG);
                    startculTime();
                }
                break;
            case R.id.tv_reset:
                if (detailInfo != null && checkSendTick()) {
                    sendCmd(detailInfo.efairydevice_id, CmdUtils.REMOTE_RESET);
                    startculTime();
                }
            case R.id.text_title_left:
                outOfSelectedType();
//                findUnhandleMsgList();
                break;
            case R.id.text_title_left2:
                if (isSeleteType) {
                    if (isAllSelect) {
                        cancalAllSelected();
                        mTitleView.getmTextLeft2().setText("全选");
                        isAllSelect = false;
                    } else {
                        isAllSelect = true;
                        mTitleView.getmTextLeft2().setText("全不选");
                        selectedAll();
                    }

                }
                break;
            case R.id.text_title_right:
                if (isSeleteType) {
                    ArrayList<Long> list = getSelectedMsgItems();
                    if (list.size() == 0) {
                        showToast("请选择需要处理的报警消息");
                        break;
                    }
                    Intent intent = new Intent(getContext(), InputAlarmActivity.class);

                    if(isAllSelect){
                        if(set.size() > 0){
                            Iterator it = set.iterator();
                           while (it.hasNext()){
                               unhandlemsg_list.remove(it.next());
                           }
                        }
                        intent.putExtra(InputAlarmActivity.KEY_MSG_ITEMS,unhandlemsg_list);
                    }else{
                        intent.putExtra(InputAlarmActivity.KEY_MSG_ITEMS, list);
                    }
                    intent.putExtra(InputAlarmActivity.KEY_DEV_ID, detailInfo.efairydevice_id);
                    startActivityForResult(intent, REQUEST_CODE_ALARM);
                    outOfSelectedType();
                } else {
                    openFilterWindow();
                }
                break;
            case R.id.img_title_left:
                finish();
                break;
            case R.id.tv_set:
                Intent intent = new Intent(getContext(), DevConfigureActivity.class);
                intent.putExtra(DevConfigureActivity.KEY_DEV_ID, detailInfo.efairydevice_id);
                startActivityForResult(intent, REQUEST_CODE_CONFIG);
                break;
            case R.id.tv_upgrade:
                queryDeviceVersionInfo();
                break;
            default:
                break;
        }
    }

    private void notifyDataSetChanged(final boolean scoller) {
        synchronized (mList) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mAdapter.notifyDataSetChanged();
                    if (scoller && mList.size() > 0) {
                        mRecyclerView.scrollToPosition(mList.size() - 1);
                        clearUnreadMsgStatus();
                    }
                }
            });
        }

    }

    /**
     * 退出选择模式
     */
    private void outOfSelectedType() {
        isSeleteType = false;
        msgChatLeftViewBinder.setSelectType(isSeleteType);
        for (Object o : mList) {
            ((MsgItem) o).isSelected = false;
        }
        mAdapter.notifyDataSetChanged();
        initCustomTitte();
        showPopWindow();

    }


    /**
     * 全不选
     */
    private void cancalAllSelected() {
        for (Object o : mList) {
            ((MsgItem) o).isSelected = false;
        }
        mAdapter.notifyDataSetChanged();

    }

    /**
     * 进入选择模式
     */
    private void entrySelectedType() {
        if (chatTipView != null)
            chatTipView.dismiss();
        isSeleteType = true;
        isAllSelect = true;
        msgChatLeftViewBinder.setSelectType(isSeleteType);
        for (Object o : mList) {
            MsgItem item = (MsgItem) o;
            if (item.get_ishandle() == 0) {
                item.isSelected = true;
            }
        }
        mAdapter.notifyDataSetChanged();
        initCustomTitte();
    }


    /**
     * 进入全部选择模式
     */
    private void selectedAll() {
        for (Object o : mList) {
            MsgItem item = (MsgItem) o;
            if (item.get_ishandle() == 0) {
                item.isSelected = true;
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 打开过滤对话框
     */
    private void openFilterWindow() {
        if (mDevChatTypeView == null) {
            mDevChatTypeView = new PopWindowDevChatTypeView(getContext());
            mDevChatTypeView.setOnViewItemClickLisenter(this);
        }
        mDevChatTypeView.show(getToolbar());
    }

    /**
     * 清空未读消息的状态
     */
    private void clearUnreadMsgStatus() {
        if (detailInfo == null)
            return;
        RongIMClient.getInstance().clearMessagesUnreadStatus(Conversation.ConversationType.PRIVATE,
                                                             "device_" + detailInfo.efairydevice_id, null);
    }

    public ArrayList<Long> getSelectedMsgItems() {
        ArrayList<Long> arrayList = new ArrayList();
        for (Object item : mList) {
            if (((MsgItem) item).isSelected) {
                arrayList.add(((MsgItem) item).get_id());
            }
        }
        return arrayList;
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return !sending.get() && canLoadMore.get() && isScrollTop.get();
    }

    @Override
    protected void onDestroy() {
        RongIMClient.setOnReceiveMessageListener(null);
        super.onDestroy();
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        getMsgData(false, false);
    }

    @Override
    public void onViewItemClick(int type) {
        boolean enabled = false;
        int color = getResources().getColor(R.color.font_gray_4);
        if (type == -1) {
            color = getResources().getColor(R.color.font_blue_dark);
            enabled = true;
        }
        textCancal.setTextColor(color);
        textReset.setTextColor(color);
        textPeizhi.setTextColor(color);
        textPeizhi.setEnabled(enabled);
        textReset.setEnabled(enabled);
        textCancal.setEnabled(enabled);
        getMsgData(true, true);
        findUnhandleMsgList();
    }






    private void showPopWindow(){
        if(chatTipView == null){
            chatTipView = new PopWindowDevChatTipView(getContext());
        }
        chatTipView.show(mTitleView, total_rows);
    }

    /**
     * 查找未处理的消息
     */
    private void findUnhandleMsgList() {
        HttpManager.getInstance().sendRequest(new GetDevUnhandleMsgListRequest(detailInfo.efairydevice_id + "", mDevChatTypeView != null ? mDevChatTypeView.getType() : -1, new Response.Listener<DeviceUnHandleResponse>() {
            @Override
            protected void onSuccess(DeviceUnHandleResponse response) {
                if (response != null && response.total_rows > 0) {
                    total_rows = response.total_rows;
                    unhandlemsg_list = response.unhandlemsg_list;
                    showPopWindow();
                }else{
                    if(chatTipView != null){
                        chatTipView.dismiss();
                    }
                }
            }

            @Override
            protected void onFail(NetworkException exception) {

            }
        }));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_ALARM || requestCode == REQUEST_CODE_CONFIG) {
                getMsgData(true, true);
                findUnhandleMsgList();
                setResult(RESULT_OK);
            }else if(requestCode == REQUEST_CODE_UPGRAD){
                addSendMsg(CmdUtils.DEVICE_UPGRADE);
            }
        } else if (!isSeleteType) {
            findUnhandleMsgList();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    private void queryDeviceVersionInfo() {
        HttpManager.getInstance().sendRequest(new GetDeviceVersionInfoRequest(detailInfo.efairydevice_id + "", new Response.Listener<CurrentDeviceInfoResponse>() {
            @Override
            protected void onSuccess(CurrentDeviceInfoResponse response) {
                if (response != null) {
                    Bundle bundle = new Bundle();
                    bundle.putString("version", response.getEfairydeviceversion_version());//软件版本
                    bundle.putString("enterprise_name", response.getEfairydevicecompanycode_name());//企业名称
                    bundle.putString("purpos", response.getEfairydeviceusagecode_name());//用途
                    bundle.putString(DevConfigureActivity.KEY_DEV_ID, detailInfo.efairydevice_id+"");
                    bundle.putString("efairydevice_version_date",detailInfo.efairydevice_version_date);
                    bundle.putString("efairydevice_version", detailInfo.efairydevice_version);

                    Intent intent2 = new Intent(getContext(), DevUpgradeActivity.class);
                    intent2.putExtras(bundle);
                    startActivityForResult(intent2,REQUEST_CODE_UPGRAD);
                } else {
                }
            }

            @Override
            protected void onFail(NetworkException exception) {
                showToast("信息获取失败");
                doException(exception);

            }
        }));
    }

}
